//
//  MYDiscoverSearchView.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/13.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

//Could not cast value of type 'UIView' (0x10631bb20) to 'MYWeibo.MYDiscoverSearchView' (0x1049e3c20).
//xib和文件没有关联

import UIKit

class MYDiscoverSearchView: UIView {

    @IBOutlet weak var searchTF: UITextField!
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var rightConstraint: NSLayoutConstraint!
    
    //xib文件不能直接在控制器中加载 应该用一个类描述它
    
    //在该方法中设置视图尺寸
    override func awakeFromNib() {
        
        //设置frame
        self.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, self.bounds.height)
        
        //设置leftView
        self.searchTF.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        
        //需要设置leftView为始终显示
        self.searchTF.leftViewMode = .Always
        
        //设置图片的间距
        self.searchTF.leftView?.frame = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height)
        
        //设置图片显示模式
        self.searchTF.leftView?.contentMode = .Center
        
        //设置按钮透明度为0
        cancelBtn.alpha = 0
        
    }
    
    //要返回一个view 所以有返回值类型
    class func loadSearchView() -> MYDiscoverSearchView {
        
        let v =  NSBundle.mainBundle().loadNibNamed("MYDiscoverSearchView", owner: nil, options: nil).last as! MYDiscoverSearchView
        
        //Cannot convert return expression of type 'AnyObject?' to return type 'MYDiscoverSearchView'
        //类型不匹配 需要强制转换
        return v
    }
    
    @IBAction func beginEdit(sender: AnyObject) {
        
        //当开始编辑时 右边的约束向左移动
        //1.先修改约束
        rightConstraint.constant = self.cancelBtn.bounds.width + 10
        //2.在动画闭包中执行动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.layoutIfNeeded()
            }) { (_) -> Void in
                
                self.cancelBtn.alpha = 1
        }
        
    }
    @IBAction func cancelClick(sender: AnyObject) {
        //结束第一响应者
        endEditing(true)
        //修改约束
        self.rightConstraint.constant = 0
        //闭包中强制刷新
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.layoutIfNeeded()
            self.cancelBtn.alpha = 0
            }) { (_) -> Void in
                print("heihei")
        }
    }

}
